#!/bin/bash

# Structural Text Analyzer MCP Server Installer
# Automates the setup process for Claude Code integration

set -e  # Exit on any error

echo "=================================================================="
echo "STRUCTURAL TEXT ANALYZER - MCP SERVER INSTALLER"
echo "=================================================================="
echo

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# Helper functions
print_step() {
    echo -e "${BLUE}🔄 $1${NC}"
}

print_success() {
    echo -e "${GREEN}✅ $1${NC}"
}

print_warning() {
    echo -e "${YELLOW}⚠️  $1${NC}"
}

print_error() {
    echo -e "${RED}❌ $1${NC}"
}

# Get installation directory
DEFAULT_INSTALL_DIR="$HOME/tools/structural_analyzer"
echo "📁 Installation Directory Options:"
echo "   1. Default: $DEFAULT_INSTALL_DIR"
echo "   2. Custom directory"
echo
read -p "Choose option (1 or 2): " install_choice

if [ "$install_choice" = "2" ]; then
    read -p "Enter custom installation directory: " INSTALL_DIR
    INSTALL_DIR="${INSTALL_DIR/#\~/$HOME}"  # Expand ~ to $HOME
else
    INSTALL_DIR="$DEFAULT_INSTALL_DIR"
fi

echo
print_step "Installing to: $INSTALL_DIR"

# Step 1: Check dependencies
print_step "Checking system dependencies..."

# Check Python
if ! command -v python3 &> /dev/null; then
    print_error "Python 3 is not installed. Please install Python 3.7+ first."
    exit 1
fi

python_version=$(python3 --version 2>&1 | awk '{print $2}')
print_success "Python 3 found: $python_version"

# Check pip
if ! command -v pip3 &> /dev/null && ! command -v pip &> /dev/null; then
    print_error "pip is not installed. Please install pip first."
    exit 1
fi

print_success "pip found"

# Step 2: Install Python dependencies
print_step "Installing Python dependencies..."

# Core dependencies
pip_cmd="pip3"
if ! command -v pip3 &> /dev/null; then
    pip_cmd="pip"
fi

echo "Installing core dependencies: numpy, pandas, scipy..."
$pip_cmd install numpy pandas scipy || {
    print_error "Failed to install core dependencies"
    exit 1
}

print_success "Core dependencies installed"

# MCP dependency (optional)
echo "Installing MCP support..."
$pip_cmd install mcp || {
    print_warning "MCP installation failed, but this is optional"
}

print_success "Python dependencies ready"

# Step 3: Create installation directory
print_step "Creating installation directory..."

mkdir -p "$(dirname "$INSTALL_DIR")"
if [ -d "$INSTALL_DIR" ]; then
    print_warning "Directory $INSTALL_DIR already exists"
    read -p "Remove existing directory? (y/N): " remove_existing
    if [ "$remove_existing" = "y" ] || [ "$remove_existing" = "Y" ]; then
        rm -rf "$INSTALL_DIR"
        print_success "Existing directory removed"
    else
        print_error "Installation cancelled"
        exit 1
    fi
fi

# Step 4: Copy files
print_step "Copying analyzer files..."

# Get the directory where this script is located
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" &> /dev/null && pwd)"

# Copy all files except the installer
cp -r "$SCRIPT_DIR" "$INSTALL_DIR"
print_success "Files copied to $INSTALL_DIR"

# Step 5: Set permissions
print_step "Setting file permissions..."

chmod +x "$INSTALL_DIR/run.sh" || print_warning "Could not make run.sh executable"
chmod +x "$INSTALL_DIR/test_mcp_server.py" || print_warning "Could not make test script executable"

print_success "Permissions set"

# Step 6: Test installation
print_step "Testing installation..."

cd "$INSTALL_DIR"
if python3 test_mcp_server.py; then
    print_success "Installation test passed"
else
    print_error "Installation test failed"
    exit 1
fi

# Step 7: Claude Code integration
echo
print_step "Claude Code Integration"
echo
echo "To add this MCP server to Claude Code, run:"
echo
echo -e "${GREEN}claude mcp add structural-text-analyzer bash $INSTALL_DIR/run.sh${NC}"
echo
echo "Or manually add this configuration to your Claude Code settings:"
echo
cat << EOF
{
  "mcpServers": {
    "structural-text-analyzer": {
      "command": "bash",
      "args": ["$INSTALL_DIR/run.sh"],
      "env": {
        "PYTHONPATH": "$INSTALL_DIR"
      }
    }
  }
}
EOF

echo
echo "=================================================================="
print_success "INSTALLATION COMPLETED SUCCESSFULLY!"
echo "=================================================================="
echo
echo "📁 Installation location: $INSTALL_DIR"
echo "🛠️  Available MCP tools: 6 analysis tools"
echo "📚 Documentation: $INSTALL_DIR/CLAUDE_MCP_INTEGRATION.md"
echo
echo "🚀 Next steps:"
echo "1. Add to Claude Code using the command above"
echo "2. Restart Claude Code"
echo "3. Test with: 'What MCP tools are available?'"
echo
echo "💡 For troubleshooting, see: $INSTALL_DIR/CLAUDE_MCP_INTEGRATION.md"
echo
